<template>
	<view class="detail">
		<view v-if="!artObj" style="padding: 30rpx;">
			<u-skeleton rows="4" title loading :animate="true"></u-skeleton>
		</view>
		<view v-else>
			<view class="container">
				<view class="title">{{artObj.title}}</view>
				<view class="left">
					<view class="userinfo">
						<view class="avatar">
							<image
								:src="artObj.user.avatar ? artObj.user.avatar : '../../static/image/user-default.png' "
								mode="aspectFill"></image>
						</view>
						<view class="info">
							<view class="name">{{artObj.user.nickname}}</view>
							<view class="time">
								<uni-dateformat :date="artObj.publishDate" format="yyyy年MM月dd日-hh:mm:ss"
									:threshold="[60000,3600000*24*30]">
								</uni-dateformat>
								-发布于{{artObj.province}}
							</view>
						</view>
					</view>
					<view class="more" @click="detelePost(artID)" v-if="isAuthor">
						<text class=" icon t-icon t-icon-gengduo"></text>
					</view>
				</view>

				<view class="content">
					<u-parse :content="artObj.content" :tagStyle="tagStyle"></u-parse>
				</view>
				<view class="like">
					<view class="btn" :class="like==false? '' :'active'" @click=" clickLike">
						<text
							:class="like==false? 'icon t-icon t-icon-dianzan' : 'icon t-icon t-icon-dianzan-copy-1' "></text>
						<text v-if=" artObj.likeCount">{{artObj.likeCount}}</text>
					</view>
				</view>
				<view class="users">
					<image src="../../static/image/user-default.png" mode="aspectFill"></image>
				</view>
				<view class="see">
					<text class="num">{{artObj.viewCount}}</text>人看过
				</view>
			</view>
			<view class="comment">
				<u-empty class="icon" v-if="!comList.length" mode="comment"
					icon="http://cdn.uviewui.com/uview/empty/comment.png">
				</u-empty>
				<view class="talk" v-if="comList.length">
					<view class="talkItme" v-for="(item,index) in comList">
						<commentList :typeNum="typeNum" :item="item" :authorComment="authorComment[index]"
							@deleteComment="PdeleteComment" :replyCommentNum="replyCommentNum[index]">
						</commentList>
					</view>
				</view>
			</view>
			<!-- 以标签的形势载入; 通过数据绑定的形势进行传值 @commentEnv是接收子组件的值,Pcomment是父组件自己的函数-->
			<talkInput :commentObj="commentObj" @commentEnv="Pcomment"></talkInput>
		</view>
	</view>
</template>

<script>
	import {
		getProvince, //获取省份
		GetStroage
	} from "../../utils/tool.js"
	import {
		getAllCommment,
		getUserComment
	} from "@/api/user.js"
	export default {
		data() {
			return {
				artID: "",
				artObj: null, //定义对象，不是字符串
				tagStyle: {
					p: "line-height:1.7em;font-size:35rpx; padding-bottom:8rpx; ",
					img: "margin:10rpx 2rpx; ",
				},
				like: false,
				isAuthor: false,
				comList: [],
				authorComment: [],
				commentObj: {
					postid: "",
					type: 0,
					uid: "",
					province: "",
				},
				userInfo: {},
				firstArr: [],
				replyCommentNum: [],
				typeNum: 0
			};
		},
		onLoad(e) {
			// console.log("详情帖子:", e.id);
			if (!e.id) {
				this.errFun();
				return;
			}
			getProvince().then(res => {
				this.commentObj.province = res;
			})
			this.artID = e.id;
			this.commentObj.postid = e.id;
			this.userInfo = GetStroage("userInfo");
			this.commentObj.uid = this.userInfo.id;
			this.updateView(this.artID); //浏览量自增1
			this.isLikePost();
			setTimeout(() => {
				this.getData(this.artID); //查询数据库
			}, 100);
			this.getComment(this.artID);
		},
		methods: {
			querySecondCommentNum(index) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: this.$e.Url + "/user/querySecondCommentNum",
						data: {
							commentId: index
						},
						header: {
							"Content-Type": "application/json"
						},
						method: "GET",
						success: (res) => {
							console.log("请求API接口【/user/querySecondCommentNum】", res);
							resolve(res.data);
						},
						fail: (err) => {
							reject(err);
						}
					})
				})
			},
			PdeleteComment(e) { //删除评论的回调
				console.log("删除评论的回调:", e);
				let index = this.comList.findIndex(item => {
					return item.id == e //注意这里是==
				});
				// console.log("---", index);
				if (index != -1) {
					this.comList.splice(index, 1); //1表示删除
				}

			},
			Pcomment(e) { //评论成功的回调
				// console.log("评论成功的回调:", e);
				this.comList.unshift({ //整个包含的有content、id、postid、province、time、type、uid、user
					...e, //传来的有content、id、province、time、uid
					...this.commentObj, //postid、type、uid、province
					user: this.userInfo //user
				})
			},
			//获取该帖子下的所有一级评论
			async getComment(index) { //将uni.request请求封装在Promise构造函数中;使用async + await;
				await this.getUserComment(this.artID, this.userInfo.id); //注意先获取它,否则authorComment可能获取长度为0
				await this.getAllCommment(index);
				console.log("一级评论的id", this.firstArr);
				for (let i = 0; i < this.firstArr.length; i++) {
					let tmp = await this.querySecondCommentNum(this.firstArr[i]);
					if (tmp == "") {
						tmp = 0;
					}
					this.replyCommentNum.push(tmp);
				}
				console.log("回复一级评论的数量", this.replyCommentNum);
			},
			getAllCommment(index) { //获取该帖子下的所有的一级评论
				return new Promise((resolve, reject) => {
					getAllCommment({
						id: index //就算是传字符串,也要这样{id:""}
					}).then(res => {
						console.log("请求API接口【/user/getAllCommment】", res);
						resolve("success")
						this.comList = res.data;
						this.comList.map(item => {
							this.$set(item, "author", false) //这下是肯定赋值了,剩余问题思考异步同步
						});
						for (let i = 0; i < res.data.length; i++) { //注意for循环的遍历方式
							this.firstArr.push(res.data[i].id);
							for (let j = 0; j < this.authorComment
								.length; j++) { //要先获取getUserComment,否则length长度为0
								if (res.data[i].uid == this.authorComment[j].uid) {
									this.comList[i].author = true;
								}
							}
						}
					}).catch(err => {
						reject(err);
					})
				})
			},
			getUserComment(index, id) { //获取用户在该帖子下的评论列表
				return new Promise((resolve, reject) => { //异步同步化
					getUserComment({
						postid: index,
						uid: id
					}).then(ans => {
						console.log("请求API接口【/user/getUserComment】", ans);
						this.authorComment = ans.data;
						resolve('suc');
					}).catch(err => {
						reject(err)
					})
				})
			},
			detelePost(index) { //删除帖子还必须删除点赞表
				uni.showModal({
					title: "删除帖子",
					content: "确定要删除吗?",
					success: (res) => {
						// console.log("帖子id:", index, "点击结果", res);
						if (res.confirm) {
							uni.request({
								url: this.$e.Url + "/user/deletePost",
								data: index, //传给前端的是data.id
								header: {
									"Content-Type": "application/json"
								},
								method: 'DELETE',
								success: (res) => {
									console.log("请求API接口【/user/deletePost】", res);
									uni.showToast({
										title: "删除成功！",
										icon: 'success'
									});
									uni.navigateBack();
								},
								fail: () => {
									uni.showToast({
										title: "删除失败",
										icon: 'error'
									})
								}
							})
						}
					}
				})
			},
			updateView(index) {
				uni.request({
					url: this.$e.Url + "/user/addPostView",
					data: index,
					header: {
						"Content-Type": "application/json"
					},
					method: 'PUT',
					success: (res) => {
						console.log("请求API接口【/user/addPostView】", res);
					}
				})
			},
			//错误处理
			errFun() {
				uni.showToast({
					title: "参数有误",
					icon: "none"
				})
				setTimeout(() => {
					uni.reLaunch({
						url: "/pages/community/community"
					})
				}, 1000) //别忘了时间
			},
			getData(index) {
				// console.log('传值:' + `${index}`);
				uni.request({
					url: this.$e.Url + "/user/getPost", //注意这里一定要加//127.0.0.1艹
					data: {
						id: index
					},
					header: {
						'Content-Type': 'application/json'
					},
					method: 'GET',
					success: (res) => {
						console.log("请求API接口【/user/getPost】", res);
						this.artObj = res.data;
						if (res.data.uid == this.userInfo.id) {
							this.isAuthor = true;
						}
					}
				})
			},
			isLikePost() { //当前用户有没有对该帖子点赞
				uni.getStorage({
					key: "userInfo",
					success: (ans) => {
						let userid = ans.data.id;
						uni.request({
							url: this.$e.Url + "/user/isLikePost",
							data: {
								uid: userid,
								postid: this.artID
							},
							header: {
								'Content-Type': 'application/json'
							},
							method: 'POST',
							success: (res) => {
								console.log("请求API接口【/user/isLikePost】", res);
								this.like = (res.data ? true : false);
							}
						})
					}
				})
			},
			clickLike() { //点赞逻辑
				uni.getStorage({
					key: "userInfo",
					success: (ans) => {
						let userid = ans.data.id;
						if (this.like) {
							uni.request({ //自减
								url: this.$e.Url + "/user/unLikePost",
								data: {
									uid: userid,
									postid: this.artID
								},
								header: {
									'Content-Type': 'application/json'
								},
								method: 'DELETE',
								success: (res) => {
									console.log("请求API接口【/user/unLikePost】", res);
									this.like = false;
									this.updatePostLike(this.artID, -1);
									this.artObj.likeCount = this.artObj.likeCount - 1;
								}
							})
						} else {
							uni.request({ //自增
								url: this.$e.Url + "/user/likePost",
								data: {
									uid: userid,
									postid: this.artID
								},
								header: {
									'Content-Type': 'application/json'
								},
								method: 'POST',
								success: (res) => {
									console.log("请求API接口【/user/likePost】", res);
									this.like = true;
									this.updatePostLike(this.artID, 1);
									this.artObj.likeCount = this.artObj.likeCount + 1;
								}
							})
						}
					}
				})
			},
			updatePostLike(id, num) { //改变帖子点赞数
				uni.request({
					url: this.$e.Url + "/user/updatePostLike",
					data: {
						id: id,
						num: num
					},
					header: {
						'Content-Type': 'application/json'
					},
					method: 'PUT',
					success: (res) => {
						console.log("请求API接口【/user/updatePostLike】", res);
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-image: url("/static/userbackground.jpg");
		background-size: cover;
		background-repeat: repeat;
		background-position: center center;
	}

	.detail {
		min-height: calc(100vh - var(--window-top));

		.container {
			background-color: #fff;
			padding: 30rpx;
			margin: 20rpx;
			border-radius: 30rpx;

			.title {
				font-size: 50rpx;
				font-weight: bold;
				color: #333;
				line-height: 1.4em;
				font-family: "微软雅黑";
			}

			.left {
				display: flex;
				align-items: center; //垂直居中
				justify-content: space-between;

				.userinfo {
					display: flex;
					align-items: center; //垂直居中
					padding: 20rpx 0 20rpx; //上右下左


					.avatar {
						width: 60rpx;
						height: 60rpx;
						padding-right: 20rpx;

						image {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}
					}

					.info {
						color: #555;
						font-size: 30rpx;

						.name {
							font-family: "楷体, Times New Roman";
						}

						.time {
							font-size: 20rpx;
							color: #999;
						}
					}
				}

				.more {
					padding: 5rpx;
				}
			}

			.content {}

			.like {
				display: flex;
				align-items: center;
				flex-direction: column; //纵向弹性
				padding: 20rpx 30rpx;

				.btn {
					width: 90rpx;
					height: 110rpx;
					background-color: #f9f9f9;
					box-shadow: 0 0 10rpx 10rpx rgba(220, 220, 220, 0.4);
					border-radius: 35rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					font-size: 30rpx;


					.icon {
						width: 55rpx;
						height: 55rpx;
					}

					&.active {
						background-color: rgba(82, 136, 245, 0.9);
						box-shadow: 0 0 10rpx 10rpx rgba(220, 220, 220, 0.4);
					}
				}
			}

			.users {
				display: flex;
				justify-content: center; //水平居中
				padding: 5rpx 30rpx;

				image {
					width: 50rpx;
					height: 50rpx;
					border-radius: 20rpx;
					// border: 1px solid #bbb;
					// margin-left: -20rpx;
				}
			}

			.see {
				display: flex;
				justify-content: center;
				font-size: 26rpx;
				color: #666;

				.num {
					color: #5288F5;
				}
			}
		}

		.comment {
			.icon {
				padding: 50rpx;
			}

			.talk {
				background-color: #ffffff;
				margin: 0rpx 30rpx;
				border-radius: 20rpx;
				box-shadow: 0 0 10rpx 10rpx rgba(199, 203, 212, 0.3);
				padding: 30rpx;
				padding-bottom: 100rpx;

				.talkItme {
					padding: 10rpx;
					border-bottom: 1rpx solid #F1F2F2;

					&:last-child {
						//最后一条评论不要底边
						border-bottom: 0rpx;
					}
				}
			}
		}
	}
</style>
